<template>
  <el-card class="box-card">
    <el-button type="primary" size="default" icon="Plus" @click="onAdd" v-has="`btn.Trademark.add`">
      添加
    </el-button>
    <!--表格-->
    <el-table style="margin: 10px 0" border stripe :data="trademarkArr">
      <el-table-column
        label="序号"
        align="center"
        width="80px"
        type="index"
      ></el-table-column>
      <el-table-column
        label="品牌名称"
        align="center"
        prop="tmName"
      ></el-table-column>
      <el-table-column label="品牌logo" align="center">
        <template #="{ row }">
          <div class="logo" style="width: 100px; margin: auto">
            <img :src="row.logoUrl" alt="暂无logo" style="width: 100%" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="onEdit(row)"
          ></el-button>
          <el-popconfirm
            :title="`是否确认删除${row.tmName}?`"
            width="200px"
            icon="Delete"
            @confirm="onDelete(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器-->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :background="true"
      :page-sizes="[10, 20, 30, 40]"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @size-change="getHasTrademark"
      @current-change="getHasTrademark"
    />
  </el-card>
  <!--弹窗-->
  <el-dialog v-model="dialogFormVisible" :title="title">
    <el-form
      style="width: 80%"
      :model="trademarkParams"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="名称" label-width="80px" prop="tmName">
        <el-input placeholder="请输入名称" v-model="trademarkParams.tmName" />
      </el-form-item>
      <el-form-item label="logo" label-width="80px" prop="logoUrl">
        <div class="upload">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onDetermine">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  Records,
  TradeMark,
  TradeMarkResponseData,
} from '@/api/product/trademark/type'
import {ElMessage, UploadProps} from 'element-plus'

let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let trademarkArr = ref<Records>([])
// 弹窗是否显示
let dialogFormVisible = ref<boolean>(false)
// 弹窗title
let title = ref<string>('添加品牌')
// 定义手机新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
// 获取el-form组件实例
let formRef = ref()
// 获取已有品牌的接口封装为一个函数
const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    pageSize.value,
  )
  if (result.code === 200) {
    trademarkArr.value = result.data.records
    total.value = result.data.total
  }
}
// 点击添加
const onAdd = () => {
  //清空收集数据
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  dialogFormVisible.value = true
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  title.value = '添加品牌'
}
// 点击修改
const onEdit = (row: TradeMark) => {
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  dialogFormVisible.value = true
  title.value = '修改品牌'
  Object.assign(trademarkParams, row)
}
// 点击删除
const onDelete = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
// 点击取消
const onCancel = () => {
  dialogFormVisible.value = false
}
// 点击确定
const onDetermine = async () => {
  await formRef.value.validate()
  let result = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code === 200) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改成功' : '添加成功',
    })
    await getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    dialogFormVisible.value = false
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改成功' : '添加成功',
    })
  }
}
// 上传图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage.error('图片大小不能超过4MB')
      return false
    }
  } else {
    ElMessage.error('暂时只支持JPG/PNG格式图片')
    return false
  }
}
// 图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response: { data: any; },
  uploadFile: any,
) => {
  trademarkParams.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}
// 名称自定义校验方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('名称位数必须大于等于两位'))
  }
}
// logo自定义校验方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('logo图片不能为空'))
  }
}
// 表单校验规则对象
const rules = {
  tmName: {required: true, trigger: 'blur', validator: validatorTmName},
  logoUrl: {required: true, validator: validatorLogoUrl},
}
onMounted(() => {
  getHasTrademark()
})
</script>
<style lang="scss">
.upload {
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
